package dba.example

import java.util.Properties
import com.google.inject.Guice
import dba.example.guice.module.ExampleModule
import org.scalatest.BeforeAndAfter
import org.scalatest.BeforeAndAfterAll
import org.scalatest.FunSuite
import javax.persistence.EntityManager
import dba.example.guice.init.Initialisation

trait ExampleGuiceInjector extends FunSuite with BeforeAndAfterAll with BeforeAndAfter {

  val injector = Guice.createInjector(new ExampleModule(loadProperties("jpa.properties")));

  override def afterAll() = {
    val init = injector.getInstance(classOf[Initialisation])
    init.stop()
  }
  
  before {
    injector.getInstance(classOf[EntityManager]).getTransaction.begin
  }  
  
  after {
    injector.getInstance(classOf[EntityManager]).getTransaction.rollback
  }  
  
  private def loadProperties(name: String) = {
    val props = new Properties()
    try {
      val is = getClass.getClassLoader.getResourceAsStream(name)
      props.load(is)
      is.close()
    } catch {
      case e: Exception => println(s"Other error $e");
    }
    props
  }

}